package com.anjue.loader
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	
	public class DllLoader extends EventDispatcher
	{
		private var loadArr:Array;
		public function DllLoader()
		{
		}
		
		public function doLoad($list:Array):void
		{
			if($list.length>0)
			{
				loadArr = $list;
				load();
				trace(loadArr[0]);
			}else
			{
				trace("no dll list!")
			}
		}
		
		private function load():void
		{
			var stream:URLStream = new URLStream();
			stream.addEventListener(Event.COMPLETE,streamCom);
			stream.load(new URLRequest(loadArr[0]));
			loadArr.splice(0,1);
		}
		
		private function streamCom(e:Event):void
		{
			var stream:URLStream = e.currentTarget as URLStream;
			stream.removeEventListener(Event.COMPLETE,streamCom);
			var by:ByteArray = new ByteArray();
			stream.readBytes(by);
			
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadCom);
			loader.loadBytes(by,new LoaderContext(false,ApplicationDomain.currentDomain));
		}
		
		private function loadCom(e:Event):void
		{
			var loader:Loader = e.currentTarget.loader as Loader;
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,loadCom);
			if(loadArr.length>0)			
			{
				load();
			}else
			{
				trace("load complete");
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}
	}
}